<template>
  <div>
    <basic-container>
      <avue-crud
        :option="tableOption"
        :data="tableData"
        :table-loading="tableLoading"
        :page="page"
        ref="crud"
        @refresh-change="handleRefreshChange"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        @selection-change="handleSelectionChange"
        @search-change="handleSearchChange"
      >
        <template slot-scope="scope" slot="menu">
          <el-button
            type="text"
            @click.stop="handleSendOrder(scope.row)"
            icon="el-icon-edit"
            v-if="scope.row.status==1"
            size="mini"
            v-perm="'user-order-item/send-order'"
          >发货</el-button>
        </template>
        <template slot="menuLeft">
          <el-button
            type="danger"
            @click="handleBatchSendOrderItems"
            icon="el-icon-edit"
            v-perm="'user_order_item/batch-send-order'"
            size="small"
          >批量发货</el-button>
          <el-button
            type="primary"
            @click="handleExport"
            :loading="downloadLoading"
            icon="el-icon-download"
            v-perm="'user_order_item/export'"
            size="small"
          >导出</el-button>
        </template>
      </avue-crud>
    </basic-container>
    <el-dialog :visible.sync="sendOrderItemFormVisible" title="发货" width="500px">
      <el-form
        :rules="sendOrderItemFormDataRules"
        :model="sendOrderItemFormData"
        ref="form1"
        label-position="left"
        label-width="80px"
      >
        <el-form-item prop="express_com_id" label="快递公司">
          <el-select
            placeholder="请选择快递公司"
            v-model="sendOrderItemFormData.express_com_id"
            filterable
          >
            <el-option v-for="com in expressComs" :key="com.id" :label="com.title" :value="com.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="express_no" label="快递单号">
          <el-input v-model="sendOrderItemFormData.express_no" placeholder="请输入快递单号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="sendOrderItemFormVisible = false">取消</el-button>
        <el-button :loading="isSubmiting" type="primary" @click="handleSendOrderItem">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  <script>
import { validatenull } from "@/util/validate";
import { getLabelFromDic } from "@/const/dic";
// import { DIC } from "@/const/dic";
import { nowDate } from "../../util/date";
import * as apiObj from "@/api/userOrderItem";
import { userOrderItemTableOption } from "@/const/userOrderItem/userOrderItemTableOption.js";

export default {
  data() {
    return {
      bachDeleting: false,
      tableOption: {}, //表格设置属性
      tableData: [], //表格的数据
      tablePage: 1,
      downloadLoading: false,
      tableLoading: false,
      tableQueryParam: {},
      expressComs: [],
      sendOrderItemFormVisible: false,
      isSubmiting: false,
      sendOrderItemFormData: {
        express_com_id: "",
        express_no: ""
      },
      sendOrderItemFormDataRules: {
        express_com_id: [
          {
            required: true,
            message: "请选择快递公司",
            trigger: "change",
            type: "number"
          }
        ],
        express_no: [
          {
            required: true,
            message: "请输入快递单号",
            trigger: "change"
          }
        ]
      },
      page: {
        total: 0, //总页数
        currentPage: 1, //当前页数
        pageSize: 10 //每页显示多少条
      }
    };
  },
  created() {
    //初始化数据格式
    this.tableOption = userOrderItemTableOption;
    this.handleList();
  },
  methods: {
    handleCurrentChange(page) {
      this.page.currentPage = page;
      this.handleList();
    },
    handleSizeChange(size) {
      this.page.pageSize = size;
      this.handleList();
    },
    handleSendOrderItem() {
      this.$refs.form1.validate(valid => {
        if (valid) {
          this.isSubmiting = true;
          const then = () => {
            this.isSubmiting = false;
            this.sendOrderItemFormVisible = false;
            this.showNotify("操作成功");
            this.handleList();
          };
          if (this.isBatchSendOrders) {
            apiObj
              .sendOrderItem(
                this.currentSelectedRowIds,
                this.sendOrderItemFormData.express_no,
                this.sendOrderItemFormData.express_com_id
              )
              .then(then);
          } else {
            apiObj
              .sendOrderItem(
                [this.currentOrderItem.id],
                this.sendOrderItemFormData.express_no,
                this.sendOrderItemFormData.express_com_id
              )
              .then(then);
          }
        }
      });
    },
    handleBatchSendOrderItems() {
      if (!this.currentSelectedRowIds || !this.currentSelectedRowIds.length) {
        this.showError("请选择至少一条记录");
        return;
      }
      this.sendOrderItemFormVisible = true;
      this.isBatchSendOrders = true;
      this.sendOrderItemFormData = {
        express_com_id: "",
        express_no: ""
      };
    },
    handleSendOrder(row) {
      this.currentOrderItem = row;
      // this.showConfirm("确认发货吗？", () => {
      //   apiObj.sendOrderItem([row.id], "", "");
      // });
      this.isBatchSendOrders = false;
      this.sendOrderItemFormVisible = true;
      this.sendOrderItemFormData = {
        express_com_id: "",
        express_no: ""
      };
    },
    handleSelectionChange(args) {
      this.currentSelectedRowIds = args.map(el => el.id);
    },
    hasChanged(params1,params2){
        return Object.keys(params1).some(key=>params2[key] != params1[key]);
    },
    handleSearchChange(params) {
      if(this.hasChanged(params,this.tableQueryParam)){
        this.page.currentPage = 1;
      }
      this.tableQueryParam = params;
      this.handleList();
    },

    handleRefreshChange() {
      this.handleList();
    },
    /**
     * @title 获取数据
     * @detail 赋值为tableData表格即可
     *
     **/
    handleList() {
      this.tableLoading = true;
      apiObj
        .list({
          pageNo: this.page.currentPage,
          pageSize: this.page.pageSize,
          ...this.tableQueryParam
        })
        .then(data => {
          this.tableData = data.rows || [];
          this.page.total = data.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },

    handleExport() {
      this.downloadLoading = true;
      apiObj
        .list({
          pageNo: 1,
          pageSize: 3000,
          ...this.tableQueryParam
        })
        .then(res => {
          import("@/vendor/Export2Excel").then(excel => {
            const tHeader = [
              "商品名称",
              "状态",
              "价格",
              "数量",
              "订单号",
              "下单时间",
              "分享购买",
              "收货人",
              "收货人地址",
              "收货人电话",
              "快递单号",
              "快递公司",
              "发货时间",
              "签收时间",
              "参与活动",
              "完成时间"
            ];
            const filterVal = [
              "title",
              "status",
              "price",
              "num",
              "order_no",
              "create_time",
              "is_share_buy",
              "receiver",
              "receiver_address",
              "receiver_telephone",
              "express_no",
              "express_com_name",
              "send_time",
              "sign_time",
              "activity_name",
              "done_time"
            ];
            const data = this.formatJson(filterVal, res.rows);
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: "商品订单列表" + nowDate()
            });
            this.downloadLoading = false;
          });
        });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          let rt = v[j];
          switch (j) {
            case "status":
              rt = getLabelFromDic("userOrderstatusDic", rt);
              break;
            case "is_share_buy":
              rt = rt == 1 ? "是" : "否";
              break;
          }
          return rt;
        })
      );
    }
  }
};
</script>
